﻿using ERCS.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;

namespace ERCS.DataAccess
{
    public class DataContext : FrameworkContext
    {

        public DbSet<Virus> Viruses { get; set; }
        public DbSet<City> Cities { get; set; }
        public DbSet<Hospital> Hospitals { get; set; }
        public DbSet<ControlCenter> ControlCenter { get; set; }
        public DbSet<Patient> Patients { get; set; }
        public DbSet<Report> Reports { get; set; }
        public DbSet<MyUser> MyUsers { get; set; }

        public DataContext(CS cs)
         : base(cs)
        {
        }

        public DataContext(string cs, DBTypeEnum dbtype)
             : base(cs, dbtype)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Patient>().HasIndex(x => x.IdNumber);
            modelBuilder.Entity<Patient>().HasOne(x => x.Location).WithMany().OnDelete(DeleteBehavior.Cascade);
            base.OnModelCreating(modelBuilder);
        }

        public override async Task<bool> DataInit(object allModules, bool IsSpa)
        {
            bool init =  await base.DataInit(allModules, IsSpa);
            if (init == true)
            {
                using (var dc = this.ReCreate())
                {
                    dc.Database.ExecuteSqlRaw("update frameworkUsers set Discriminator='MyUser' where Itcode='admin'");
                }
            }
            return init;
        }
    }

    /// <summary>
    /// 为EF的Migration准备的辅助类，填写完整连接字符串和数据库类型
    /// 就可以使用Add-Migration和Update-Database了
    /// </summary>
    public class DataContextFactory : IDesignTimeDbContextFactory<DataContext>
    {
        public DataContext CreateDbContext(string[] args)
        {
            return new DataContext("Server=(localdb)\\mssqllocaldb;Database=ERCS_db4;Trusted_Connection=True;", DBTypeEnum.SqlServer);
        }
    }

}
